<?php

namespace app\admin\controller\general;

use app\admin\library\Auth;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\db\exception\BindParamException;
use think\exception\DbException;
use think\exception\PDOException;
use think\response\Json;
use function fast\e;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Quyu extends Backend
{

    /**
     * Quyu模型对象
     * @var \app\admin\model\general\Quyu
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\general\Quyu;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        $lists=$list->items();


        foreach ($lists as &$key){
            $key['name']=$key['text'];

            $user=Db::name('user')->where(['id'=>$key['user_id']])->find();

            if ($user){
                $key['user_name']=$user['nickname'];
            }



        }


        $result = ['total' => $list->total(), 'rows' => $lists];
        return json($result);
    }


    public function indexs()
    {
        //设置过滤方法

        $list =Db::name('aa_quyu')->select();

        foreach ($list as &$key){
            $key['name']=$key['text'];
        }


        $result = ['total' => count($list), 'rows' => $list];
        return json($result);
    }

    public function upfile(){


        $ids=$this->request->param('ids');

        $this->assign('dis',$ids);


        if ($this->request->isPost()){

            $file=$this->request->param('file');
            $quyu_id=$this->request->param('quyu_id');
            $this->imports($file,$quyu_id);

            $this->success();
        }

        return $this->view->fetch();


    }


    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    protected function imports($file='',$quyu_id='')
    {

        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }


       if ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];

        //加载文件
        $insert = [];

        if (!$PHPExcel = $reader->load($filePath)) {
            $this->error(__('Unknown data format'));
        }
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);


        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $fields = [];


            $types=$currentSheet->getCellByColumnAndRow(4, $currentRow)->getValue();
            $fields['types'] = $types=='目标客户'?1:0;


            $fields['seetime'] = $currentSheet->getCellByColumnAndRow(2, $currentRow)->getValue();

            $fields['address'] = $currentSheet->getCellByColumnAndRow(3, $currentRow)->getValue();
            $fields['name'] = $currentSheet->getCellByColumnAndRow(5, $currentRow)->getValue();

            $fields['c_name'] = $currentSheet->getCellByColumnAndRow(7, $currentRow)->getValue();
            $fields['c_mobile'] = $currentSheet->getCellByColumnAndRow(8, $currentRow)->getValue();
            $fields['c_wx'] = $currentSheet->getCellByColumnAndRow(9, $currentRow)->getValue();

            $fields['level'] = $currentSheet->getCellByColumnAndRow(10, $currentRow)->getValue();
            $fields['shoper'] = $currentSheet->getCellByColumnAndRow(11, $currentRow)->getValue();
            $fields['seat1'] = $currentSheet->getCellByColumnAndRow(12, $currentRow)->getValue();
            $fields['seat2'] = $currentSheet->getCellByColumnAndRow(13, $currentRow)->getValue();
            $fields['month'] = $currentSheet->getCellByColumnAndRow(14, $currentRow)->getValue();
            $fields['test'] = $currentSheet->getCellByColumnAndRow(15, $currentRow)->getValue();
            $fields['testr'] = $currentSheet->getCellByColumnAndRow(16, $currentRow)->getValue();


            $fields['rival_name'] = $currentSheet->getCellByColumnAndRow(17, $currentRow)->getValue();
            $fields['rival_desc'] = $currentSheet->getCellByColumnAndRow(18, $currentRow)->getValue();
            $fields['desc'] = $currentSheet->getCellByColumnAndRow(19, $currentRow)->getValue();

            $fields['image'] ='https://lingdaotea.vipwjf.com/uploads/20250102/b25669d0fab2056aff5ae0aa75e79881.jpg';
            $fields['wimages'] ='https://lingdaotea.vipwjf.com/uploads/20250102/b25669d0fab2056aff5ae0aa75e79881.jpg';
            $fields['quyu_id'] =$quyu_id;
            $fields['time'] =time();



//            var_dump($fields);


            Db::name('aa_client')->data($fields)->insert();

        }




        $this->success();
    }

    public function getallquyu(){

        $list=Db::name('aa_quyu')->alias('a')
            ->join('fa_user b','a.user_id=b.id')
            ->field('a.*,b.nickname')
            ->select();

        foreach ($list as &$key){

            $key['name']=$key['text'].$key['nickname'];
        }


        return json($list);



    }

}
